package com.suyuan.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.suyuan.dao.*;
import com.suyuan.entity.*;
import com.suyuan.service.OrderService;
import com.suyuan.vo.OrderDetailVO;
import com.suyuan.vo.OrderInfoVO;
import com.suyuan.vo.OrderItemVO;
import com.suyuan.web.Page;
import com.suyuan.web.PageData;
import org.apache.commons.collections.OrderedMap;
import org.hibernate.criterion.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单
 */
@Service(value = "orderService")
@Transactional
public class OrderServiceImpl implements OrderService{

    @Resource
    private OrderInfoMapper orderMapper;
    @Resource
    private OrderitemInfoMapper orderItemMapper;
    @Resource
    private CustomCartItemMapper cartItemMapper;
    @Resource
    private CustomerCartMapper cartMapper;
    @Resource
    private ProductInfoMapper productMapper;
    @Resource
    private CustomAddrMapper addrMapper;
    @Resource
    private CustomInfoMapper customMapper;
    @Resource
    private CompanyInfoMapper companyInfoMapper;

    public boolean saveOrder(String itemIds, Integer userId,Integer addrId) {
        try {
            //保存订单时选择的地址信息
            CustomAddr addr = addrMapper.findOne(addrId);
            //购物车对象
            CustomInfo custom = customMapper.selectByPrimaryKey(userId);
            CustomerCart cart = cartMapper.selectByPrimaryKey(custom.getGid());

            // 1.新建订单对象,初始化数据后持久化
            OrderInfo order = new OrderInfo();
            order.setOrdertime(new Date());
            order.setOrderstate("1");// 1代表未付款 2代表已付款  3 订单完成未评价 4代表评价完成
            order.setCustomid(userId);
            order.setEmployeeid(userId);
            order.setRealpaymoney(0f);//初始值
            order.setNormalmoney(0d);//初始值
            order.setDiscount(1f);//折扣不知道填哪个商品，默认不打折。为1
            //将地址信息添加进去
            order.setOrderaddr(addr.getAddr());
            order.setOrderphone(addr.getRecePhone());
            order.setReceivername(addr.getReceName());

            //在mapper.xml中的方法配置，插入后可直接拿到对象的主键
            //useGeneratedKeys="true" keyProperty="gid" keyColumn="GID"
            int orderCode = orderMapper.insert(order);
            if(orderCode == 0){
                System.out.println("订单创建失败");
                return false;
            }
            //订单对象初始化完毕

            //2.查找出所有购物项
            String[] ids = itemIds.split(",");
            for(String itemId : ids){
                CustomCartItem cartItem = cartItemMapper.findById(Integer.parseInt(itemId));
                if(cartItem != null){
                    //将购物项添加进订单，并删除该购物项，购物车总价减去相应小计
                    ProductInfo product = productMapper.selectByPrimaryKey(cartItem.getProductId());
                    //将每个购物项添加为订单项
                    OrderitemInfo orderItem = new OrderitemInfo();
                    orderItem.setOrderid(order.getGid());//订单id
                    orderItem.setCompid(product.getCompid());//生产企业
                    orderItem.setProductid(product.getProductid());//产品编号
                    orderItem.setProccount(cartItem.getProCount().floatValue());//产品数量
                    orderItem.setProceunit(product.getProcunit());//单位
                    orderItem.setProcprice(product.getProcprice());//单价
                    orderItem.setProcamount(cartItem.getSubtotal().floatValue());//订单项总价 = 购物项小计
                    orderItem.setProcdiscount(product.getProcdiscount());//折扣
                    orderItem.setProccost(cartItem.getSubtotal().floatValue() * product.getProcdiscount());//实际金额= 总价 * 折扣
                    orderItem.setFinishcount(cartItem.getProCount().floatValue());//交付数量
                    orderItem.setFinishstate("1");// 1代表未付款 2代表已付款  3 订单完成未评价 4代表评价完成
                    //保存订单前查看库存是否充足
                    Float count = product.getProccount();
                    if(count < cartItem.getProCount()){
                        System.out.println("编号为："+product.getProductid()+"的商品库存不足，此次生成订单失败");
                        break;//订单不充足时，直接跳过当前订单的生成逻辑
                    }
                    orderItemMapper.insert(orderItem);

                    //更新商品库存
                    Float newCount = count - cartItem.getProCount();
                    product.setProccount(newCount);
                    productMapper.updateByPrimaryKey(product);

                    //将每个购物项中的原价格，实付金额。迭代添加进订单中
                    Double newNormalMoney =  cartItem.getSubtotal().add(new BigDecimal(order.getNormalmoney())).doubleValue();
                    //Float newRealMoney = (cartItem.getSubtotal().floatValue() * product.getProcdiscount()) + order.getRealpaymoney() ;
                    order.setNormalmoney(newNormalMoney);//原价格
                    order.setRealpaymoney(newNormalMoney.floatValue());
                    //order.setRealpaymoney(newRealMoney);//实际价格
                }
                //将购物车中相关的购物项去除
                cartItemMapper.delete(Integer.parseInt(itemId));

                //购物车中总价减去每个购物项的小计
                BigDecimal newTotal = cart.getTotal().subtract(cartItem.getSubtotal());
                cart.setTotal(newTotal);
            }
            //更新订单
            order.setFinishedtime(new Date());
            orderMapper.updateByPrimaryKey(order);
            //更新购物车
            cartMapper.updateByPrimaryKey(cart);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public List<OrderInfoVO> myOrders(Integer id) {
        OrderInfoExample orderExample = new OrderInfoExample();
        OrderInfoExample.Criteria criteria = orderExample.createCriteria();
        criteria.andCustomidEqualTo(id);
        List<OrderInfo> orders = orderMapper.selectByExample(orderExample);
        //我的订单集合信息（包装后）
        List<OrderInfoVO> orderVOs = new ArrayList<OrderInfoVO>();

        //获取订单项
        for(OrderInfo order : orders){
            OrderitemInfoExample itemExample = new OrderitemInfoExample();
            OrderitemInfoExample.Criteria itemCriteria = itemExample.createCriteria();
            itemCriteria.andOrderidEqualTo(order.getGid());
            List<OrderitemInfo> items = orderItemMapper.selectByExample(itemExample);

            //每个订单项VO集合
            List<OrderItemVO> itemVOs = new ArrayList<OrderItemVO>();
            for(OrderitemInfo item : items){
                ProductInfo product = productMapper.selectByPrimaryKey(item.getProductid());
                CompanyInfo company = companyInfoMapper.selectByPrimaryKey(item.getCompid());

                OrderItemVO itemVO = new OrderItemVO();
                itemVO.setImages(product.getImagesrc());
                itemVO.setCompanyName(company.getCompname());
                itemVO.setOrderItemId(item.getOrderitemid()+"");
                itemVO.setProductCount(item.getProccount()+"");
                itemVO.setProductName(product.getProductname());
                itemVO.setProductPrice(product.getSellprice()+"");
                itemVO.setProductUnit(item.getProceunit());
                itemVOs.add(itemVO);
            }

            OrderInfoVO orderInfoVO = new OrderInfoVO();
            orderInfoVO.setOrder(order);
            orderInfoVO.setItems(itemVOs);
            orderVOs.add(orderInfoVO);
        }
        return orderVOs;
    }

    public OrderDetailVO orderDetail(Integer id) {
        OrderInfo order = orderMapper.selectByPrimaryKey(id);
        if(order == null){
            System.out.println("订单不存在");
            return null;
        }
        OrderitemInfoExample example = new OrderitemInfoExample();
        OrderitemInfoExample.Criteria criteria = example.createCriteria();
        criteria.andOrderidEqualTo(order.getGid());
        //订单项集合
        List<OrderitemInfo> items = orderItemMapper.selectByExample(example);

        //订单项字段整理
        List<OrderItemVO> itemVOs = new ArrayList<OrderItemVO>();

        for(OrderitemInfo item : items){
            ProductInfo product = productMapper.selectByPrimaryKey(item.getProductid());
            CompanyInfo company = companyInfoMapper.selectByPrimaryKey(item.getCompid());

            OrderItemVO itemVO = new OrderItemVO();
            itemVO.setImages(product.getImagesrc());
            itemVO.setCompanyName(company.getCompname());
            itemVO.setOrderItemId(item.getOrderitemid()+"");
            itemVO.setProductCount(item.getProccount()+"");
            itemVO.setProductName(product.getProductname());
            itemVO.setProductPrice(product.getSellprice()+"");
            itemVO.setProductUnit(item.getProceunit());

            itemVOs.add(itemVO);
        }

        return new OrderDetailVO(order,itemVOs);
    }



    //后台查询所有用户订单
    public List<OrderInfo> findAllOrder() {
        return orderMapper.selectByExample(null);
    }

    //删除订单
    public void deleteOrder(Integer id) {
        orderMapper.deleteByPrimaryKey(id);
    }

    //根据订单ID查询订单
    public OrderInfo findOrderByGid(Integer id) {
        return   orderMapper.selectByPrimaryKey(id);
    }

    //更新用户订单
    public void updateOrderInfo(OrderInfo orderInfo) {
       OrderInfo activceOrderInfo =   orderMapper.selectByPrimaryKey(orderInfo.getGid());
       activceOrderInfo.setNormalmoney(orderInfo.getNormalmoney());
       activceOrderInfo.setRealpaymoney(orderInfo.getRealpaymoney());
       activceOrderInfo.setDiscount(orderInfo.getDiscount());
       activceOrderInfo.setFinishedtime(orderInfo.getFinishedtime());
       activceOrderInfo.setOrderaddr(orderInfo.getOrderaddr());
       activceOrderInfo.setOrderphone(orderInfo.getOrderphone());
       activceOrderInfo.setOrdertime(orderInfo.getOrdertime());
       activceOrderInfo.setOrderstate(orderInfo.getOrderstate());
       activceOrderInfo.setReceivername(orderInfo.getReceivername());
       activceOrderInfo.setRecmemo(orderInfo.getRecmemo());
       orderMapper.updateByPrimaryKey(activceOrderInfo);
    }


}
